const path = require('path')
const router = require('koa-router')()
const Sequelize = require('sequelize')
const fileModel = require('../../models/file')
const fs = require('fs')
const koaJwt = require('koa-jwt')
const jwt = require('jsonwebtoken')
const bodyParser = require('koa-bodyparser')

const dao = require('../../dao/' + path.basename(__dirname))

const routerUploadAndDownloadVariable = require('../../config/file_service')

// 此jwtPassword仅是Upload和Download路由所使用的常量
const jwtPassword = routerUploadAndDownloadVariable.jwtPassword

// changePath 变量所指向的绝对路径是指向/wepan文件夹下面的
const changePath = routerUploadAndDownloadVariable.changePath
// 文件储存在磁盘中的地址
const address = routerUploadAndDownloadVariable.address
/*
    修改文件在磁盘中的存储格式；
    1 为真实路径（存储在文件夹下，文件名为真实文件名），0 为虚拟路径（所有文件存储在一个文件夹内，文件名为文件哈希值）
 */
const saveType = routerUploadAndDownloadVariable.saveType

// 此路由使用 Body 传参
router.post('/', async (ctx, next) => {
    try {

        await bodyParser()

        // 解析jwt
        const decode = await jwt.verify(ctx.request.body.fields.auth, jwtPassword)
        const postParams = ctx.request.body
        //const decode = ctx.request.body
        //const decode = await jwt.decode(ctx.request.query.auth)
        //ctx.status = 200
        //ctx.body = { decode, postParams }
        console.log(postParams); console.log(decode)


        // 上传多个文件
        const file = postParams.files.file; // 获取上传文件
        //const file = decode.files.file; // 获取上传文件
        console.log(file);

        /*

        // 生成hash
        const fsHash = crypto.createHash('md5')
        const buffer = fs.readFileSync(file.path)
        fsHash.update(buffer);
        const fileHash = fsHash.digest('hex')

         */

        const fileHash = file.hash
        const fileName = file.name
        let newName = file.name

        // 修改同名BUG, 在 saveType === 1 的时候启用

        if(saveType) {

            let findFile = await fileModel.findOne({
                where: {
                    name: fileName,
                    //directory: file.directory
                }
            })

            let number = 0
            while (findFile.length !== 0) {
                number++
                const newName = file.name + '(' + number.toString() + ')'
                findFile = await fileModel.findOne({
                    where: {
                        name: newName,
                        directory: file.directory
                    }
                })
            }

            if (number) newName = file.name + '(' + number.toString() + ')'
        }

        // 写入磁盘之中
        const reader = fs.createReadStream(file.path)
        let filePath
        if (saveType)
            filePath = path.join(changePath, address, file.directory) + `/${file.name}`
        else
            filePath = path.join(changePath, address) + `/${fileHash}`
        const upStream = fs.createWriteStream(filePath)
        reader.pipe(upStream)

        // 添加到数据库内
        await fileModel.create({
            name: newName,
            hash: fileHash,
            size: file.size,
            directory : file.directory,
            location: filePath,
            is_directory: false,
            deleted_at: null,
            is_starred: false
        })
        console.log('base Success')

        // 路由响应
        ctx.status = 200
        ctx.body = {
            message: 'A New Uploaded file !\n',
            size : file.size,
            fileName : file.name,
            hash : fileHash,
            directory: file.directory
        }

    }
    catch (err) {
        if(err.status === 401) {
            ctx.status = 401
            ctx.body = {
                message :'Protected resource, use Authorization header to get access\n'
            }
        }
        else {
            ctx.status = 500
            ctx.body = {
                message: err.message
                //test : ctx.request.query.auth
            }
        }
        // await next()
    }
})


module.exports = router.routes();